#!/bin/sh

#=======================================================================
# git-dangling
# File ID: 13613774-3334-11e0-bfdc-fefdb24f8e10
# Create branches on every dangling commit
# License: GNU General Public License version 2 or later.
#=======================================================================

progname=git-dangling
bannedfile=$HOME/.git-dangling-banned
dangfile=.git/dangling-result.tmp

store_blobs=0
if test "$1" = "-b"; then
    store_blobs=1
    shift
fi

if test "$1" = "-c"; then
    # Check if commit-* branches are part of any other branch
    for f in $(git branch | cut -c 3- | grep '^commit-'); do
        echo ============ $progname: $f
        git branch -a --contains=$f | grep -v "^  $f\$"
    done
    exit
fi

# Delete all commit-* branches
git branch | cut -c 3- | grep -E '^commit-[0-9a-f]{40}$' | grep -Ev commit-0{40} | xargs -r git branch -D

# Delete all tag-* tags
git tag | grep -E '^tag-[0-9a-f]{40}$' | while read f; do
    git tag -d "$f"
done

test "$1" = "-D" && exit

cd "$(git rev-parse --show-toplevel)" || {
    echo $progname: Could not chdir to top level of repo >&2
    exit 1
}
test -d .git/. || dangfile=$(basename $dangfile)

git fsck --no-reflogs >$dangfile
for f in `grep "^dangling commit" $dangfile | cut -f 3 -d ' '`; do
    git branch commit-$f $f && echo $progname: Creating commit-$f
done
for f in `grep "^dangling tag" $dangfile | cut -f 3 -d ' '`; do
    git tag tag-$f $f && echo $progname: Creating tag-$f
done
if test "$store_blobs" = "1"; then
    for f in `grep "^dangling blob" $dangfile | cut -f 3 -d ' '`; do
        git show $f >blob-$f && echo $progname: Creating blob-$f
    done
fi
git delete-banned
test "$dangfile" = "$(basename $dangfile)" && rm $dangfile
echo $progname: New branches:
git branch | git nocom -r
exit 0
